﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Test.Site.Models;

namespace Test.Site.Controllers
{
	[HandleError]
	public class HomeController : Controller
	{
		[Authorize]
		public ActionResult Index()
		{
			return View();
		}

		[HttpGet]
		public ActionResult Login(string returnUrl)
		{
			return View();
		}

		[HttpPost]
		public ActionResult Login(LoginModel model, string returnUrl)
		{
			if (ModelState.IsValid)
			{
				// TODO Add Authentication
				Response.SetCookie(new HttpCookie(FormsAuthentication.FormsCookieName)
				{
					HttpOnly = true,
					Expires = DateTime.UtcNow.Add(FormsAuthentication.Timeout),
					Value = FormsAuthentication.Encrypt(new FormsAuthenticationTicket(
						1,
						model.UserName,
						DateTime.Now,
						DateTime.Now.Add(FormsAuthentication.Timeout),
						true,
						Guid.NewGuid().ToString()
					))
				});

				if (!string.IsNullOrEmpty(returnUrl))
				{
					return Redirect(returnUrl);
				}

				return RedirectToAction("Index");
			}

			return View(model);
		}

		[Authorize]
		public ActionResult Logout()
		{
			FormsAuthentication.SignOut();
			return RedirectToAction("Login");
		}
	}
}
